package com.itshen.one.controller;

import com.alibaba.fastjson.JSONObject;
import com.itshen.annotation.PassToken;
import com.itshen.annotation.UserLoginToken;
import com.itshen.entity.User;
import com.itshen.service.TokenService;
import com.itshen.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @copyright: stephen
 * @author: stephen.shen
 * @email: shenzhaoxiang@gmail.com
 * @create: 2018-11-30 16:28
 */
@Api(tags = "JWT测试")
@RestController
@RequestMapping("/auth")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    TokenService tokenService;

    /**
     * 登录
     */
    @PassToken
    @PostMapping("/login")
    public Object login(@RequestBody User user) {
        JSONObject jsonObject = new JSONObject();
        User userForBase = userService.findByUsername(user);
        if (userForBase == null) {
            jsonObject.put("message", "登录失败,用户不存在");
            return jsonObject;
        } else {
            if (!userForBase.getPassword().equals(user.getPassword())) {
                jsonObject.put("message", "登录失败,密码错误");
                return jsonObject;
            } else {
                String token = tokenService.getToken(userForBase);
                jsonObject.put("token", token);
                jsonObject.put("user", userForBase);
                return jsonObject;
            }
        }
    }

    /**
     * 需要token才能访问
     *
     * @return
     */
    @UserLoginToken
    @GetMapping("/getMessage")
    public String getMessage() {
        return "你已通过验证";
    }


}